/*
** list.c for list in /home/hubert_s//test/list_C
** 
** Made by sevan hubert
** Login   <hubert_s@epitech.net>
** 
** Started on  Tue Feb  8 14:16:47 2011 sevan hubert
** Last update Tue Jun 28 14:00:37 2011 sevan hubert
*/

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

t_list	 *alloc_list()
{
  t_list *new;

  new = (t_list*)xmalloc(sizeof(*new));
  if (new == NULL)
    {
      printf("Error malloc : can not allocate memory.\n");
      exit(0);
    }
  return (new);
}

void	init_list(t_list *to_init)
{
  if (to_init)
    {
      to_init->begin = NULL;
      to_init->end = NULL;
      to_init->size = 0;
      to_init->is_empty = 1;
    }
}

void	put_begin_list(t_list *list, item *to_put)
{
  if (list && to_put)
    {
      list->size = list->size + 1;
      if (list->is_empty)
	{
	  list->is_empty = 0;
	  list->begin = to_put;
	  list->end = to_put;
	  to_put->next = NULL;
	}
      else
	{
	  to_put->next = list->begin;
	  list->begin = to_put;
	  to_put->next->prev = to_put;
	}
      to_put->prev = NULL;
    }
}

void	put_end_list(t_list *list, item *to_put)
{
  if (list && to_put)
    {
      list->size = list->size + 1;
      if (list->is_empty)
	{
	  list->is_empty = 0;
	  list->begin = to_put;
	  list->end = to_put;
	  to_put->prev = NULL;
	}
      else
	{
	  to_put->prev = list->end;
	  list->end = to_put;
	  to_put->prev->next = to_put;
	}
      to_put->next = NULL;
    }
}

void	remove_item_in_list(t_list *list, item *to_remove)
{
  if (!list || !to_remove || list->is_empty)
    return ;
  if (!to_remove->prev)
    list->begin = to_remove->next;
  else
      to_remove->prev->next = to_remove->next;
  if (!to_remove->next)
    list->end = to_remove->prev;
  else
    to_remove->next->prev = to_remove->prev;
  list->size -= 1;
  if (list->size == 0)
    list->is_empty = 1;
}

void	remplace_item_in_list(t_list *list, item *to_remove, item *to_put)
{
  if (!list || !to_remove || !to_put || list->is_empty)
    return ;
  to_put->next = to_remove->next;
  to_put->prev = to_remove->prev;
  if (!to_put->prev)
    list->begin = to_put;
  else
    to_put->prev->next = to_put;
  if (!to_put->next)
    list->end = to_put;
  else
    to_put->next->prev = to_put;
}
